package service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONObject;
import object.TradeAddr;
import object.Transaction;
import object.UserCenter;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pojo.Commodity;
import pojo.LogIncome;
import pojo.LogNoruserbill;
import pojo.TransactionDetails;
import pojo.TransactionLog;
import pojo.User;
import utils.GetHelper;
import utils.HttpRequestUtil;
import utils.OrderNumUtil;
import utils.weixin.WeixinUtil;
import config.ConstantConfig;
import config.SysConfig;
import dao.TransactionDao;
import dao.UserDao;

/**
 * 
 * @author zgy
 *
 */
@Service("TransactionService")
public class TransactionService {
	
	private static Logger logger = Logger.getLogger(TransactionService.class);
	
	@Autowired
	private TransactionDao transactionDao;
	@Autowired
	private UserDao userDao;
	
	public List<Commodity> queryCommodity(Integer curPage,Integer pageSize){
		return transactionDao.queryCommodityList(curPage, pageSize);
	}
	
	public List<TradeAddr> queryTradeAddr(String platformId){
		return transactionDao.queryTradeAddrList(platformId);
	}
	
	public List<Transaction> queryTransaction(String platformId){
		return transactionDao.queryTransactionList(platformId);
	}
	
	public List<TransactionDetails> queryTransactionDetail(String orderNum){
		return transactionDao.queryTransactionDetailList(orderNum);
	}
	
	public List<TransactionLog> queryTransactionLog(String orderNum){
		return transactionDao.queryTransactionLogList(orderNum);
	}
	
	public List<Transaction> queryCompleteTrade(String platformId){
		return transactionDao.queryCompleteTrade(platformId);
	}
	
	public List<LogNoruserbill> queryUserBillList(Integer userId){
		return transactionDao.queryUserBillList(userId);
	}
	
	public List<LogIncome> queryIncomeList(Integer userId){
		return transactionDao.queryIncomeList(userId);
	}
	
	public Transaction queryTransactionByOrder(String orderNum){
		return transactionDao.queryTransaction(orderNum);
	}
	
	public UserCenter queryUserCenter(String platformId){
		return transactionDao.queryUserCenter(platformId);
	}
	
	public boolean commitTransaction(pojo.Transaction transaction,String platformId,String commodityIds,String goodsNums){
		User user = userDao.getUserByWxID(platformId);
		if(user!=null){
			String []commodityID = commodityIds.split(",");
			String []goodsNum = goodsNums.split(",");
			transaction.setUserID(user.getUserID());
			if(transactionDao.insertTransaction(transaction)){
				for(int i=0;i<commodityID.length;i++){
					Commodity commodity = transactionDao.queryCommodityById(Integer.parseInt(commodityID[i]));
					pojo.TransactionDetails details = new TransactionDetails();
					details.setDescription(commodity.getDescription());
					details.setGoodsName(commodity.getName());
					details.setGoodsNum(Integer.parseInt(goodsNum[i]));
					//details.setGoodsPrice(commodity.getPrice().multiply(new BigDecimal(Integer.parseInt(goodsNum[i]))));
					details.setGoodsPrice(commodity.getPrice());
					details.setOrderNum(transaction.getOrderNum());
					transactionDao.insertTransactionDetails(details);
				}
				pojo.TransactionLog transactionLog = new pojo.TransactionLog();
				transactionLog.setDescription("【用户下单】");
				transactionLog.setOrderNum(transaction.getOrderNum());
				transactionLog.setTime(transaction.getStartTime());
				transactionLog.setUserID(transaction.getUserID());
				transactionDao.insertTransactionLog(transactionLog);
				
				JSONObject josn=HttpRequestUtil.httpRequestRjson(SysConfig.showMsgBox_url, "POST", "processId=register-1"
						+ "&apt.title=邮宝洗衣&apt.type=1-3-代理商管理员,[textAndUrl=http://service.24box.cn/transactionAction!list?isAjax=false%26isClear=true]"
						+ "&apt.applicant.orgType=1&apt.applicant.agentId=1&apt.applicant.orgId=1"
						+ "&apt.applicant.orgName=邮宝代理商&apt.applicant.userType=user"
						+ "&apt.applicant.userId="+user.getUserID()+"&apt.applicant.userName=微信洗衣");
				return true;
			}else{
				logger.warn("insertTransaction failed");
				return false;
			}
		}else{
			logger.warn("user is null");
			return false;
		}
		
	}
	
	public boolean updateTransaction(pojo.Transaction transaction,String platformId,String commodityIds,String goodsNums){
		User user = userDao.getUserByWxID(platformId);
		if(user!=null){
			String []commodityID = commodityIds.split(",");
			String []goodsNum = goodsNums.split(",");
			transaction.setUserID(user.getUserID());
			if(transactionDao.updateTransaction(transaction)){
				if(transactionDao.deleteTransactionDetails(transaction.getOrderNum())){
					for(int i=0;i<commodityID.length;i++){
						Commodity commodity = transactionDao.queryCommodityById(Integer.parseInt(commodityID[i]));
						pojo.TransactionDetails details = new TransactionDetails();
						details.setDescription(commodity.getDescription());
						details.setGoodsName(commodity.getName());
						details.setGoodsNum(Integer.parseInt(goodsNum[i]));
						details.setGoodsPrice(commodity.getPrice().multiply(new BigDecimal(Integer.parseInt(goodsNum[i]))));
						details.setOrderNum(transaction.getOrderNum());
						transactionDao.insertTransactionDetails(details);
					}
					pojo.TransactionLog transactionLog = new pojo.TransactionLog();
					transactionLog.setDescription("【修改订单】");
					transactionLog.setOrderNum(transaction.getOrderNum());
					transactionLog.setTime(new Timestamp(System.currentTimeMillis()));
					transactionLog.setUserID(transaction.getUserID());
					transactionDao.insertTransactionLog(transactionLog);
					return true;
				}else{
					logger.warn("deleteTransactionDetails failed");
					return false;
				}
			}else{
				logger.warn("updateTransaction failed");
				return false;
			}
		}else{
			logger.warn("user is null");
			return false;
		}
	}
	
	public boolean clearAddrStatus(String platformId){
		User user = userDao.getUserByWxID(platformId);
		if(user!=null){
			if(transactionDao.clearAddrStatus(user.getUserID())){
				return true;
			}else{
				logger.warn("clearAddrStatus failed");
				return false;
			}
		}else{
			logger.warn("user is null");
			return false;
		}
		
	}
	
	public boolean insertTradeAddr(pojo.TransactionAddr transactionAddr,String platformId){
		User user = userDao.getUserByWxID(platformId);
		if(user!=null){
			transactionAddr.setUserID(user.getUserID());
			if(transactionDao.insertTradeAddr(transactionAddr)){
				return true;
			}else{
				logger.warn("insertTradeAddr failed");
				return false;
			}
		}else{
			logger.warn("user is null");
			return false;
		}
		
	}
	
	public boolean updateTradeAddr(pojo.TransactionAddr transactionAddr){
		if(transactionDao.updateTradeAddr(transactionAddr)){
			return true;
		}else{
			logger.warn("updateTradeAddr failed");
			return false;
		}
	}
	
	public boolean deleteTradeAddr(pojo.TransactionAddr transactionAddr){
		if(transactionDao.deleteTradeAddr(transactionAddr)){
			return true;
		}else{
			logger.warn("deleteTradeAddr failed");
			return false;
		}
	}
	
	public boolean cancelTransaction(pojo.Transaction transaction){
		Transaction t = transactionDao.queryTransaction(transaction.getOrderNum());
		if(ConstantConfig.TRANSACTION_STATUS_ORDER.equals(t.getStatus())){
			if(transactionDao.cancelTransaction(transaction)){
				return true;
			}else{
				logger.warn("cancelTransaction failed");
				return false;
			}
		}else{
			logger.warn("status is not 0");
			return false;
		}
	}
	
	@Transactional
	public boolean payTransaction(String orderNum,int payType){
		Transaction t = transactionDao.queryTransaction(orderNum);
		if(ConstantConfig.TRANSACTION_NOTPAY.equals(t.getPayment())){
			if(transactionDao.payTransaction(orderNum)){
				pojo.TransactionLog transactionLog = new pojo.TransactionLog();
				String description="【您已支付订单】";
				if(payType==4){
					description="【您已[微信]支付订单】";
				}else if(payType==1){
					description="【您已[账户]支付订单】";
				}
				transactionLog.setDescription(description);
				transactionLog.setOrderNum(orderNum);
				transactionLog.setTime(new Timestamp(System.currentTimeMillis()));
				transactionLog.setUserID(t.getUserID());
				transactionDao.insertTransactionLog(transactionLog);
				return true;
			}else{
				logger.warn("payTransaction failed");
				return false;
			}
		}else{
			logger.warn("payment is not 0");
			return false;
		}
	}
	
	public boolean isUserRegistered(String openid){
		User user = userDao.getUserByWxID(openid);
		if(user!=null){
			return true;
		}else{
			return false;
		}
	}
	
	public String queryTransactionStatus(String orderNum){
		String status="";
		if(orderNum.indexOf("YBXYR")!=-1){
			status=transactionDao.queryLogIncomeStatus(orderNum);
		}else{
			status=transactionDao.queryTransactionPayStatus(orderNum);
		}
		return status;
	}
	//要有事务,要锁行
	@Transactional
	public boolean updateTransactionStatus(String openId,String orderNum,String wxOrderNum,BigDecimal money){
		boolean flag=false;
		BigDecimal balance=transactionDao.queryUserBalance(openId);
		if(orderNum.indexOf("YBXYR")!=-1){
			balance=balance.add(money.divide(new BigDecimal(100)));
			flag=transactionDao.updateLogIncomeStatus(orderNum, wxOrderNum,balance);
			flag=transactionDao.updateUserBalance(balance, openId);
		}else{
			//flag=transactionDao.updateNorUserBillStatus(orderNum, wxOrderNum,new BigDecimal(0) );
			flag=transactionDao.updateNorUserBillStatus(orderNum, wxOrderNum,balance );
			flag=payTransaction(orderNum, ConstantConfig.PAYTYPE_WX);
		}
		return flag;
	}
	
	public boolean insertLogBill(String platformId,String orderNum,BigDecimal money){
		boolean flag=false;
		UserCenter userCenter=queryUserCenter(platformId);
		if(orderNum.indexOf("YBXYR")!=-1){
			LogIncome income=new LogIncome(new Integer(5),userCenter.getUserId(),
					userCenter.getLastName()+userCenter.getFirstName(),
					new Integer(1),userCenter.getUserId(),
					new Timestamp(new Date().getTime()),money,
					new BigDecimal(0),ConstantConfig.PAYTYPE_WX,orderNum,ConstantConfig.TRANSACTION_NOTPAY);
			flag=transactionDao.insertLogIncome(income);
		}else{
			Integer count=transactionDao.queryNorUserBillCount(orderNum);
			if(!(count>0)){
				LogNoruserbill noruserbill=new LogNoruserbill(userCenter.getUserId(), new Timestamp(new Date().getTime()), 
						money, new BigDecimal(0), ConstantConfig.LogNorUSerBill_XY, 
						"【邮宝洗衣扣费】", ConstantConfig.PAYTYPE_WX, userCenter.getMobileNum(), 
						orderNum,ConstantConfig.LogNorUSerBill_WXPAY, ConstantConfig.TRANSACTION_NOTPAY);
				flag=transactionDao.insertNorUserBill(noruserbill);
			}else{
				flag=true;
			}
		}
		return flag;
	}
	
	@Transactional
	public boolean ybPayTransaction(String openId,String orderNum,BigDecimal money){
		boolean flag=false;
		UserCenter userCenter=queryUserCenter(openId);
		BigDecimal balance=userCenter.getBalance();
		if(balance.compareTo(money)!=-1){
			balance=balance.subtract(money) ;
			LogNoruserbill noruserbill=new LogNoruserbill(userCenter.getUserId(), new Timestamp(new Date().getTime()), 
					money,balance , ConstantConfig.LogNorUSerBill_XY, 
					"【邮宝洗衣扣费】", ConstantConfig.PAYTYPE_YB, userCenter.getMobileNum(), 
					OrderNumUtil.createTradeNumber(),ConstantConfig.LogNorUSerBill_COUNTPAY, ConstantConfig.TRANSACTION_PAYED);
			flag=transactionDao.insertNorUserBill(noruserbill);
			flag=transactionDao.updateUserBalance(balance, openId);
			flag=payTransaction(orderNum,ConstantConfig.PAYTYPE_YB);
		}
		return flag;
		
	}
	
}